package com.wuxianedu.servive;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button start, stop, bind, unbind;
    private Intent intent, bindIntent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intent = new Intent(this, MyService.class);
        bindIntent = new Intent(this, MyBindService.class);
        initView();
        initListener();
    }

    private void initListener() {
        start.setOnClickListener(this);
        stop.setOnClickListener(this);
        bind.setOnClickListener(this);
        unbind.setOnClickListener(this);
    }

    private void initView() {
        start = (Button) findViewById(R.id.start);
        stop = (Button) findViewById(R.id.stop);
        bind = (Button) findViewById(R.id.bind);
        unbind = (Button) findViewById(R.id.unbind);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start: //开启服务
                startService(intent);

                break;
            case R.id.stop:
                stopService(intent);
                break;

            case R.id.bind:
                //conn: 与service建立联系
                //固定写法，BIND_AUTO_CREATE
                bindService(bindIntent, conn, BIND_AUTO_CREATE);
                break;
            case R.id.unbind:
                if (conn != null){
                    unbindService(conn);
                    conn = null;
                }
                break;

        }
    }

    MyConn conn = new MyConn();

    class MyConn implements ServiceConnection {

        //成功绑定时被回调
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("-------------","--------onServiceConnected-------");
            IService service1 = (IService) service;
            service1.fun();
        }

        // 绑定不成功时被回调
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("-------------","--------onServiceDisconnected-------");
        }
    }
}
